package com.example.xiaolu.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.xiaolu.mapper.UserMapper;
import com.example.xiaolu.model.domain.User;
import com.example.xiaolu.service.impl.UserServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSON;

import java.util.List;


@RestController
@RequestMapping("/users")
public class controller {
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserServiceImpl userService;

    @PostMapping("/register")
    public long register(@RequestParam("userAccount") String userAccount,
                         @RequestParam("userPassword") String userPassword,
                         @RequestParam("checkPassword") String checkPassword) {
        return userService.userRegister(userAccount, userPassword, checkPassword);
    }

    @PostMapping("/login")
    public User login(@RequestParam("userAccount") String userAccount,
                        @RequestParam("userPassword") String userPassword,
                        HttpServletRequest request) {
        return userService.userLogin(userAccount, userPassword, request);
    }

    @GetMapping("/delete")
    public boolean delete(@RequestParam String userAccount, HttpServletRequest request) {
        if (judge(request)) {
            QueryWrapper<User> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("userAccount",userAccount);
            return userService.remove(queryWrapper);
        }
        return false;
    }
    @GetMapping("/search")
    public String search(@RequestParam String userAccount, HttpServletRequest request) {
        System.out.println(userAccount);
        if (judge(request)){
            QueryWrapper<User> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("userAccount",userAccount);
            System.out.println(JSON.toJSON(userMapper.selectOne(queryWrapper)));
            return JSON.toJSON(userMapper.selectOne(queryWrapper)).toString();
        }
        return null;
    }
    @GetMapping("/all")
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }
    @PutMapping("/update")
    public String updateUser(@RequestBody User user) {
        boolean result = userService.updateUser(user);
        if (result) {
            return "更新成功";
        } else {
            return "更新失败";
        }
    }

    public boolean judge(HttpServletRequest request) {
        System.out.println(request.getSession().getAttribute("userLoginState"));
        Object object = request.getSession().getAttribute("userLoginState");
        User user = (User) object;
        System.out.println(67);
        System.out.println(user);
        return user != null && user.getUserRole() == 1;
    }
}